package com.undsf.util;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Arathi on 2015/10/19.
 */
public class CsvFile {
    private List<String> lines;
    private Map<String, Block> blocks;

    public CsvFile(String path){
        init(path);
        buildBlocks();
    }

    public void init(String path){
        lines = new ArrayList<>();
        try {
            //FileReader reader = new FileReader(path);
            InputStream is = this.getClass().getResourceAsStream(path);
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = null;
            while ( ( line=bufferedReader.readLine() ) != null) {
                lines.add(line);
            }
            //System.out.println( "从" + path + "读取" + lines.size() + "行数据" );
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    public Map<String, Block> buildBlocks(){
        blocks = new HashMap<>();
        Block block = null;
        for (int index = 0; index < lines.size(); index++) {
            String line = lines.get(index);
            if (line.startsWith("#")){
                if (block != null){
                    blocks.put(block.getName(), block);
                }
                String name = line.substring(1);
                if (name.equals("EOF")){
                    break;
                }
                block = new Block(name, index);
                continue;
            }
            Value row = new Value(line);
            block.addRow(row);
        }
        return blocks;
    }

    public Block getBlock(String tag) {
        Block block = blocks.get(tag);
        return block;
    }

    public String getLine(int index) {
        return lines.get(index);
    }

    public int getLineAmount(){
        if (lines == null) {
            return 0;
        }
        return lines.size();
    }
}
